package com.gisuni.sddc.platformManager.service;

import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.gisuni.sddc.platformManager.dao.LogDao;

import com.gisuni.sddc.platformManager.model.Response;
import com.gisuni.sddc.util.ExcelOperation;
import com.gisuni.sddc.util.StringUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@IocBean
public class LogService  {
	
	private  Log log = Logs.getLog(LogService.class);
//	private Log log = Logs.getLog(LogService.class);    
    @Inject
    private LogDao  logDao;
    
    public Response addLog(com.gisuni.sddc.platformManager.model.Log logs) {
    	 Response res = new Response();
    	 res.setSuccess(false);
    	 try{
 
    		 String orgId = UUID.randomUUID().toString().replaceAll("-", "");
    		 logs.setId(orgId);
    		 logs.setCreateTime(new Date());
    		 
    		 //保存 
    		 boolean flag  = logDao.addLog(logs);

    				 
    		 if(flag){
    			 res.setSuccess(true);
    			 res.setMsg("操作成功");
    		 } 
    	 }catch(Exception e){
       		 log.error(e);
       		 res.setMsg("操作失败");
       		 throw e;
       	 }
		 
		return res;
    }


	public Response findGrid(int page, int size,HttpServletRequest request) {
		Response response = new Response();
		response.setSuccess(false);
		try{
			String userName = request.getParameter("userName");
			String startDate = request.getParameter("startDate");
			String endDate = request.getParameter("endDate");
			
			if(StringUtil.isNullOrEmpty(startDate)){
				startDate = "2010-01-01";
			}
			if(StringUtil.isNullOrEmpty(endDate)){
				endDate = "2050-01-01";
			}
			
			int from = (page-1)*size;
			int to = page*size;
			StringBuffer resultSbf = new StringBuffer();
			StringBuffer countResult = new StringBuffer();		
			countResult.append( "select count(1) sizes from (");
			resultSbf.append(" select * from (select t.*,rownum rws   from (select * from SDDCGISPLATFORM.log   order by  create_time desc) t ");
			resultSbf.append(" where t.create_time >= to_date('"+startDate+"','yyyy-MM-dd') and t.create_time <= to_date('"+endDate+"','yyyy-MM-dd')+1");
			countResult.append(resultSbf.toString()+"))");
			resultSbf.append( " and rownum <="+to+" ) where rws >"+from +" order by  create_time desc");
			
			String result = logDao.findData(resultSbf.toString());
			int total = logDao.findRows(countResult.toString());
			response.setSuccess(true);
			response.setResult(result);
			response.setTotal(total);
			return response;
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			response.setMsg("查询失败");
			return response;
		}

	}
	
	/**
	 * 导出Excel
	 * @param departmentType
	 * @param projectType
	 * @param startdate
	 * @param enddate
	 * @param response
	 * @throws Exception
	 */
	public void exportLogExcel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		String filetitle = null;
		String[] rowsName = null;
		String[] columnTop = null;
		Response responseStr = findGrid(1,10000000,request);
 
			filetitle = "日志";
			rowsName = new String[] { "序号", "用户","日志类型", "状态","信息", "时间"  };
			columnTop = new String[] { "", "USER_NAME","TYPE", "STATUS","INFO","CREATE_TIME" };
	 
		String resultStr = (String) responseStr.getResult();
		JSONArray resultJsonArr = new JSONArray(resultStr);
		List<Map> Result = new ArrayList<Map>();
		if (resultJsonArr != null && resultJsonArr.length() > 0) {
			DecimalFormat    df   = new DecimalFormat("######0.00"); 
			for (int i = 0; i < resultJsonArr.length(); i++) {
				JSONObject ret = (JSONObject) resultJsonArr.get(i);
				Iterator iterator = ret.keys();
				Map map = new HashMap();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = (String) ret.get(key);
					if("TYPE".equals(key)){
						if("1".equals(value)){
							value = "登录日志";
						}
					}
					if("STATUS".equals(key)){
						if("1".equals(value)){
							value = "成功";
						}else if("2".equals(value)){
							value = "失败";
						}
					}
					 
					map.put(key, value);
				}
				Result.add(map);
			}
		}
		ExcelOperation excle = new ExcelOperation();
		excle.export(filetitle, rowsName, columnTop, Result, response);
	}
	
 

}
